<?php

namespace app\common\service;

use app\common\service\Base;

class OrderSize extends Base
{

	/**
	 * 根据ID获取记录信息
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		$info = db('order_size')->where('mid', $id)->field($field)->findOrEmpty();
		if (isset($info['wheat_low_count_detail'])) {
			$info['wheat_low_count_detail'] = $info['wheat_low_count_detail'] != '' ? json_decode($info['wheat_low_count_detail'], true) : [];
		}
		if(isset($info['wheat_height_count_detail'])) {
			$info['wheat_height_count_detail'] = $info['wheat_height_count_detail'] != '' ? json_decode($info['wheat_height_count_detail'], true) : [];
		}
		if (isset($info['wheat_low_bundle_detail'])) {
			$info['wheat_low_bundle_detail'] = $info['wheat_low_bundle_detail'] != '' ? json_decode($info['wheat_low_bundle_detail'], true) : [];
		}
		if(isset($info['wheat_height_bundle_detail'])) {
			$info['wheat_height_bundle_detail'] = $info['wheat_height_bundle_detail'] != '' ? json_decode($info['wheat_height_bundle_detail'], true) : [];
		}
		return $info;
	}

	/**
	 * 根据订单号获取尺码列表
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 * @param integer $orderId
	 * @param string $field
	 * @return array
	 */
	public function getListByOrderId($orderId, $field='*') {
		if (empty($orderId)) return [];
		$list = db('order_size')->where('order_id', $orderId)->field($field)->order('mid asc')->select();
		foreach ($list as $k => $v) {
			if (isset($v['wheat_low_count_detail'])) {
				$list[$k]['wheat_low_count_detail'] = $v['wheat_low_count_detail'] != '' ? json_decode($v['wheat_low_count_detail'], true) : [];
			}
			if(isset($v['wheat_height_count_detail'])) {
				$list[$k]['wheat_height_count_detail'] = $v['wheat_height_count_detail'] != '' ? json_decode($v['wheat_height_count_detail'], true) : [];
			}

			if (isset($v['wheat_low_bundle_detail'])) {
				$list[$k]['wheat_low_bundle_detail'] = $v['wheat_low_bundle_detail'] != '' ? json_decode($v['wheat_low_bundle_detail'], true) : [];
			}
			if(isset($v['wheat_height_bundle_detail'])) {
				$list[$k]['wheat_height_bundle_detail'] = $v['wheat_height_bundle_detail'] != '' ? json_decode($v['wheat_height_bundle_detail'], true) : [];
			}
		}
		return $list;
	}

	/**
	 * 获取下单数
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getOrderCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('order_count');
	}

	/**
	 * 获取实裁数
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getShicaiCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('shicai_count');
	}

	/**
	 * 获取车间交货数
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getJiaohuoCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('jiaohuo_count');
	}

	/**
	 * 获取尾部交货数
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getJiaohuoTailCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('jiaohuo_tail_count');
	}

	/**
	 * 获取mes发货数
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getDeliveryCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('delivery_count');
	}

	/**
	 * 获取到货数（出货数）
	 *
	 * @author KING
	 * @date 2020年7月22日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @param string $sizeName	尺码
	 * @return number
	 */
	public function getDaohuoCount($orderIds, $sizeName='') {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		if ($sizeName != '') $where[] = ['size_name', '=', $sizeName];
		return db('order_size')->where($where)->sum('daohuo_count');
	}

	/**
	 * 根据条件获取下单件数(已完成订单)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @return integer
	 */
	public function getOrderCountByRange($startTime, $endTime, $factoryId=0, $andWhere='') {
		$where = [
			['o.status', '=', 2],
			['o.over_time', 'between', [$startTime, $endTime]],
		];
		if ($factoryId != '') $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order_size os')->join('order o', 'os.order_id = o.id')->where($where)->where($andWhere)->sum('os.order_count');
	}

	/**
	 * 根据条件获取实裁件数(裁床已完成)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @param bool $exceptTail		是否去除尾货
	 * @return integer
	 */
	public function getShicaiCountByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0, $exceptTail=false) {
		$where = [
			['o.caichuang_status', '=', 1],
			['o.caichuang_over_time', 'between', [$startTime, $endTime]],

		];
		if ($exceptTail) {
			$where[] = ['stock_type','not in','10,11'];
		}
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId != '') $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order_size os')->join('order o', 'os.order_id = o.id')->where($where)->where($andWhere)->sum('os.shicai_count');
	}

	/**
	 * 根据条件获取交货件数(车间已完成)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getJiaohuoCountByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.chejian_status', '=', 1],
			['o.chejian_over_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId != '') $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order_size os')->join('order o', 'os.order_id = o.id')->where($where)->where($andWhere)->sum('os.jiaohuo_count');
	}

	/**
	 * 根据条件获取出货件数(已完成订单+已打包订单)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getDaohuoCountByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.tail_status', '=', 1],
			['o.tail_over_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId != '') $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		return db('order_size os')->join('order o', 'os.order_id = o.id')->where($where)->where($andWhere)->sum('os.daohuo_count');
	}

	/**
	 * 获取指定时间段内的数量（下单数/实裁数/车间数/尾部数/出货数）
	 *
	 * @author KING
	 * @date 2020年5月21日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param string $timeField
	 * @param string $countField
	 * @param integer $isAutoImport
	 * @return integer
	 */
	public function getCountByRange($startTime, $endTime, $factoryId=0, $andWhere='', $timeField='o.create_time', $countField='os.order_count', $isAutoImport=0) {
		$where = [];
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$where[] = [$timeField, 'between', [$startTime, $endTime]];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		return db('order_size os')->join('order o', 'os.order_id = o.id')->where($where)->where($andWhere)->sum($countField);
	}


	/**
	 * 根据条件获取出货金额(已完成订单+已打包)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return number
	 */
	public function getDaohuoMoneyByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', 'in', [0, 1, 2]],
			['o.tail_status', '=', 1],
			['o.tail_over_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$info = db('order_size os')->join('order o', 'os.order_id = o.id')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->fieldRaw("sum(os.daohuo_count * s.cost) as num")->findOrEmpty();
		return round(arrayGet($info, 'num', 0), 2);
	}

	/**
	 * 根据条件获取下单金额(已完成订单)
	 *
	 * @author KING
	 * @date 2020年4月17日
	 *
	 * @param integer $startTime
	 * @param integer $endTime
	 * @param integer $factoryId
	 * @param string $andWhere
	 * @param integer $isAutoImport
	 * @return number
	 */
	public function getOrderMoneyByRange($startTime, $endTime, $factoryId=0, $andWhere='', $isAutoImport=0) {
		$where = [
			['o.status', '=', 2],
			['o.tail_status', '=', 1],
			['o.over_time', 'between', [$startTime, $endTime]],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$info = db('order_size os')->join('order o', 'os.order_id = o.id')->join('sku s', 's.sku = o.sku')->where($where)->where($andWhere)->fieldRaw("sum(os.order_count * s.cost) as num")->findOrEmpty();
		return round(arrayGet($info, 'num', 0), 2);
	}

	/**
	 * 获取年度营业额（本年1月1日起的 FOB+CMT+新CMT 的总出货金额）
	 *
	 * @author KING
	 * @date 2018年6月24日
	 *
	 * @param string $factoryId
	 * @param string $isAutoImport
	 */
	public function getYearMoney($factoryId=0, $isAutoImport=0) {
		$yearTime = strtotime(date('Y-01-01 00:00:00'));
		$where = [
			['o.status', '=', 2],
			['o.over_time', '>=', $yearTime],
		];
		if ($isAutoImport) {
			$where[] = ['o.is_auto_import', '=', $isAutoImport];
		}
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		$list = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku')->where($where)->field('o.o_type,os.daohuo_count,s.price,s.cost')->select();
		$money = 0;
		foreach ($list as $k => $v) {
			$v = (array) $v;
			if ($v['o_type'] == 'FOB') $money += $v['daohuo_count'] * $v['price'];
			elseif ($v['o_type'] == 'CMT') $money += $v['daohuo_count'] * $v['cost'];
			elseif ($v['o_type'] == 'CMT2') $money += $v['daohuo_count'] * $v['cost'];
		}
		return round($money);
	}

	/**
	 * 获取月度完成情况（件数、金额、加工费）
	 *
	 * @author KING
	 * @date 2018年6月24日
	 *
	 * @param integer $factoryId
	 * @param integer $isAutoImport
	 */
	public function getMonthCompleteData($factoryId=0, $isAutoImport=0) {
		$monthTime = strtotime(date('Y-m-01 00:00:00'));
		$where = [
			['o.status', '=', 2],
			['o.over_time', '>=', $monthTime],
		];
		if ($factoryId) $where[] = ['o.factory_id', is_numeric($factoryId)?'=':'in', $factoryId];
		if ($isAutoImport) $where[] = ['o.is_auto_import', '=', $isAutoImport];
		$list = db('order_size os')->join('order o', 'o.id = os.order_id')->join('sku s', 's.sku = o.sku')->where($where)->field('o.o_type,os.order_count,os.daohuo_count,s.price,s.cost')->select();

		$count = 0;	// 件数
		$money = 0; // 金额
		$cost = 0;  // 加工费
		$list = $list?:[];
		foreach ($list as $k => $v) {
			// 件数
			$count += $v['order_count'];

			// 金额
			if ($v['o_type'] == 'FOB') $money += $v['daohuo_count'] * $v['price'];
			elseif ($v['o_type'] == 'CMT') $money += $v['daohuo_count'] * $v['cost'];
			elseif ($v['o_type'] == 'CMT2') $money += $v['daohuo_count'] * $v['cost'];

			// 加工费
			$cost = $v['order_count'] * $v['cost'];
		}
		return ['count' => $count, 'money' => $money, 'cost' => $cost];
	}


	/**
	 * 更新订单
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param array $data
	 * @param array $where
	 * @return number
	 */
	public function updateInfo($data, $where=[]) {
		$data['update_time'] = time();
		$upRet= db('order_size')->where($where)->update($data);
        $order_sizeinfo=db('order_size')->where($where)->find();
        $orderSizeArr=db('order_size')->where('order_id',$order_sizeinfo['order_id'])->select();
        $material_shicai_count=0;
        foreach ($orderSizeArr as $k => $val) {
            $material_shicai_count+=$val['shicai_count'];
        }
        db('order_material')->where('order_id',$order_sizeinfo['order_id'])->update(['shicai_count'=>$material_shicai_count]);
        return $upRet;
	}
}